﻿Imports Equipment.Core
Imports Equipment.DataAccess
Imports Equipment.Business
Imports Equipment.Model

Namespace Equipment
    <RequiresAuthentication()> _
    Public Class AssetController
        Inherits System.Web.Mvc.Controller

        <RequiresPageAcces(Page:=PageType.AssetMaintain)> _
        Function Index() As ActionResult

            Dim sites As IEnumerable(Of SiteDepartment) = SiteDepartmentManager.GetAllSitesFor(Application.CurrentUserInfo)
            Dim departments As IEnumerable(Of SiteDepartment) = New List(Of SiteDepartment)
            ViewData("Department") = New SelectList(departments, "ID", "Description")

            Dim assetList As IEnumerable(Of Asset) = AssetManager.GetAllBySiteFor(Application.CurrentUserInfo)

            ViewData("AssetType") = New SelectList(AssetType.RetrieveAll(), "ID", "Description")
            ViewData("Site") = New SelectList(sites, "ID", "Description")
            ViewData("Assets") = assetList
            ViewData("Statuses") = AssetStatus.RetrieveAll()
            ViewData("EntityType") = EntityType.Asset
            Return View()
        End Function

        Function Details(ByVal id As Integer) As ActionResult
            Return View()
        End Function

#Region "Create"
        <RequiresPageAcces(Page:=PageType.AssetCreate)> _
        Function Create() As ActionResult
            InitAssetPageElements()
            Return View()
        End Function

        <HttpPost()> _
        <RequiresPageAcces(Page:=PageType.AssetCreate)> _
        Function Create(ByVal collection As FormCollection) As ActionResult

            Dim selectedDepartmentID As Integer = 0
            Dim selectedAssetTypeID As Integer = 0

            Dim formAssetName As String = collection("AssetName")
            Dim formModelNo As String = collection("ModelNo")
            Dim formSerialNo As String = collection("SerialNo")
            Dim formDepartmentID As String = collection("Department")
            Dim formAssetTypeID As String = collection("AssetType")
            Dim formBarcodeID As String = collection("BarcodeID")

            Dim changeDetails As New List(Of String)

            Dim predefinedFieldList = AssetCustomField.RetrieveAllByType(CustomFieldType.Predefined)

            If Not Integer.TryParse(formDepartmentID, selectedDepartmentID) Then
                selectedDepartmentID = 0
            End If


            If Not Integer.TryParse(formAssetTypeID, selectedAssetTypeID) Then
                selectedAssetTypeID = 0
            End If

            Try

                Dim fieldSetting As AssetCustomField = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.AssetBarcode)

                If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                    If String.IsNullOrEmpty(formBarcodeID) Then
                        ModelState.AddModelError("BarcodeID", "Barcode ID is required.")
                    End If
                End If

                fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.AssetName)

                If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                    If String.IsNullOrEmpty(formAssetName) Then
                        ModelState.AddModelError("AssetName", "Name is required.")
                    End If
                End If

                fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.ModelNo)

                If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                    If String.IsNullOrEmpty(formModelNo) Then
                        ModelState.AddModelError("ModelNo", "Model # is required.")
                    End If
                End If


                fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.SerialNo)

                If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                    If String.IsNullOrEmpty(formSerialNo) Then
                        ModelState.AddModelError("SerialNo", "Serial # is required.")
                    End If
                End If

                fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.AssetType)

                If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                    If String.IsNullOrEmpty(formAssetTypeID) Or formAssetTypeID = "0" Then
                        ModelState.AddModelError("AssetType", "Asset Type is required.")
                    End If
                End If


                If String.IsNullOrEmpty(formDepartmentID) Then
                    ModelState.AddModelError("Department", "Site Department is required.")
                End If

                Dim newAsset As New Asset()

                newAsset.AssetName = formAssetName
                newAsset.ModelNo = formModelNo
                newAsset.SerialNo = formSerialNo
                newAsset.SiteDepartmentID = formDepartmentID
                newAsset.AssetTypeID = formAssetTypeID
                newAsset.BarcodeID = formBarcodeID

                If Not String.IsNullOrEmpty(formAssetName) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Asset Name", formAssetName))
                End If

                If Not String.IsNullOrEmpty(formModelNo) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Model #", formModelNo))
                End If

                If Not String.IsNullOrEmpty(formSerialNo) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Serial No", formSerialNo))
                End If

                If Not String.IsNullOrEmpty(formBarcodeID) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Bar Code", formBarcodeID))
                End If

                If Not String.IsNullOrEmpty(formAssetTypeID) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Asset Type", AssetType.GetByPrimaryKey(formAssetTypeID).Description))
                End If

                If Not String.IsNullOrEmpty(formDepartmentID) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Department", SiteDepartment.GetByPrimaryKey(formDepartmentID).Description))
                End If

                Dim status As AssetStatus = AssetStatus.GetByStatusName("New")

                If status IsNot Nothing Then
                    newAsset.AssetStatusID = AssetStatus.GetByStatusName("New").ID
                Else
                    ModelState.AddModelError("Status", "Status 'New' is not defined in references.")
                End If

                For Each field In AssetCustomField.RetrieveAllActiveByType(CustomFieldType.DropDown)
                    Dim formFieldValue As String = collection(String.Format("ddField_{0}", field.ID))
                    Dim newField As New AssetField()
                    newField.FieldName = field.FieldName
                    newField.FieldValue = formFieldValue
                    newField.SourceID = field.ID
                    newAsset.Fields.Add(newField)
                    If field.Mandatory AndAlso String.IsNullOrEmpty(formFieldValue) Then
                        ModelState.AddModelError(String.Format("ddField_{0}", field.ID), String.Format("{0} is required.", field.FieldName))
                    End If
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, field.FieldName, formFieldValue))
                    ViewData(String.Format("ddField_{0}", field.ID)) = formFieldValue
                Next

                For Each field In AssetCustomField.RetrieveAllActiveByType(CustomFieldType.Text)
                    Dim formFieldValue As String = collection(String.Format("textField_{0}", field.ID))
                    Dim newField As New AssetField()
                    newField.FieldName = field.FieldName
                    newField.FieldValue = formFieldValue
                    newField.SourceID = field.ID
                    newAsset.Fields.Add(newField)
                    If field.Mandatory AndAlso String.IsNullOrEmpty(formFieldValue) Then
                        ModelState.AddModelError(String.Format("textField_{0}", field.ID), String.Format("{0} is required.", field.FieldName))
                    End If
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, field.FieldName, formFieldValue))
                    ViewData(String.Format("textField_{0}", field.ID)) = formFieldValue
                Next

                Dim selectedSiteId As Integer = 0
                Dim department As SiteDepartment = SiteDepartment.GetByPrimaryKey(selectedDepartmentID)
                If department IsNot Nothing Then
                    selectedSiteId = department.ParentID
                End If

                If Not ModelState.IsValid Then
                    InitAssetPageElements(selectedAssetTypeID, selectedDepartmentID, selectedSiteId, "AssetName", formAssetName, _
                      "ModelNo", formModelNo, "SerialNo", formSerialNo, "BarcodeID", formBarcodeID)
                    Return View()
                End If

                Asset.Insert(newAsset)
                ModificationHistory.Insert(EntityType.Asset, formAssetName, ModificationAction.Created, Application.CurrentUserInfo.UserID, changeDetails, newAsset.AssetID, newAsset.SiteDepartment.ParentID)
                NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.Asset_Create, newAsset.AssetName, newAsset)


                Return RedirectToAction("Index")
            Catch
                Return View()
            End Try
        End Function
#End Region

#Region "Edit"
        <RequiresPageAcces(Page:=PageType.AssetEdit)> _
        Function Edit(ByVal id As Integer) As ActionResult
            Dim assetToEdit As Asset = Asset.GetByPrimaryKey(id)

            If assetToEdit IsNot Nothing Then
                ViewData("AssetID") = assetToEdit.AssetID
                ViewData("AssetName") = assetToEdit.AssetName
                ViewData("ModelNo") = assetToEdit.ModelNo
                ViewData("SerialNo") = assetToEdit.SerialNo
                ViewData("BarcodeID") = assetToEdit.BarcodeID
                ViewData("StatusID") = assetToEdit.AssetStatusID
                ViewData("Statuses") = AssetStatus.RetrieveAll()
                ViewData("EntityID") = assetToEdit.AssetID
                ViewData("EntityType") = EntityType.Asset

                InitAssetPageElements(assetToEdit.AssetTypeID, assetToEdit.SiteDepartmentID, assetToEdit.SiteDepartment.ParentID)

                For Each field In assetToEdit.Fields
                    If field.AssetCustomField.FieldType = CustomFieldType.Text Then
                        ViewData(String.Format("textField_{0}", field.SourceID)) = field.FieldValue
                    Else
                        ViewData(String.Format("ddField_{0}", field.SourceID)) = field.FieldValue
                    End If
                Next

            End If

            Return View()
        End Function

        <HttpPost()> _
        <RequiresPageAcces(Page:=PageType.AssetEdit)> _
        Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult

            Dim selectedDepartmentID As Integer = 0
            Dim selectedAssetTypeID As Integer = 0

            Dim changeDetails As New List(Of String)

            Dim formAssetName As String = collection("AssetName")
            Dim formModelNo As String = collection("ModelNo")
            Dim formSerialNo As String = collection("SerialNo")
            Dim formDepartmentID As String = collection("Department")
            Dim formAssetTypeID As String = collection("AssetType")
            Dim formBarcodeID As String = collection("BarcodeID")
            'Dim formAssetStatusID As Integer = Integer.Parse(collection("AssetStatus"))

            Dim predefinedFieldList = AssetCustomField.RetrieveAllByType(CustomFieldType.Predefined)

            If Not Integer.TryParse(formDepartmentID, selectedDepartmentID) Then
                selectedDepartmentID = 0
            End If


            If Not Integer.TryParse(formAssetTypeID, selectedAssetTypeID) Then
                selectedAssetTypeID = 0
            End If


            Try

                Dim assetToEdit As Asset = Asset.GetByPrimaryKey(id)

                If assetToEdit IsNot Nothing Then

                    ViewData("EntityID") = assetToEdit.AssetID
                    ViewData("EntityType") = EntityType.Asset

                    Dim fieldSetting As AssetCustomField = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.AssetBarcode)

                    If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                        If String.IsNullOrEmpty(formBarcodeID) Then
                            ModelState.AddModelError("BarcodeID", "Barcode ID is required.")
                        End If
                    End If

                    fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.AssetName)

                    If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                        If String.IsNullOrEmpty(formAssetName) Then
                            ModelState.AddModelError("AssetName", "Name is required.")
                        End If
                    End If

                    fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.ModelNo)

                    If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                        If String.IsNullOrEmpty(formModelNo) Then
                            ModelState.AddModelError("ModelNo", "Model # is required.")
                        End If
                    End If


                    fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.SerialNo)

                    If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                        If String.IsNullOrEmpty(formSerialNo) Then
                            ModelState.AddModelError("SerialNo", "Serial # is required.")
                        End If
                    End If

                    fieldSetting = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = AssetFieldType.AssetType)

                    If fieldSetting IsNot Nothing AndAlso fieldSetting.Mandatory Then
                        If String.IsNullOrEmpty(formAssetTypeID) Or formAssetTypeID = "0" Then
                            ModelState.AddModelError("AssetType", " vcyAsset Type is required.")
                        End If
                    End If

                    If String.IsNullOrEmpty(formDepartmentID) Then
                        ModelState.AddModelError("Department", "Site Department is required.")
                    End If

                    Dim oldAssetName = assetToEdit.AssetName
                    Dim oldModelNo = assetToEdit.ModelNo
                    Dim oldSerialNo = assetToEdit.SerialNo
                    Dim oldDepartment = assetToEdit.SiteDepartment.Description
                    Dim oldAssetType = assetToEdit.AssetType.Description
                    Dim oldBarcodeID = assetToEdit.BarcodeID

                    assetToEdit.AssetType = assetToEdit.DBContext.AssetTypes.Single(Function(at) at.ID = formAssetTypeID)
                    assetToEdit.AssetName = formAssetName
                    assetToEdit.ModelNo = formModelNo
                    assetToEdit.SerialNo = formSerialNo
                    assetToEdit.SiteDepartment = assetToEdit.DBContext.SiteDepartments.SingleOrDefault(Function(l) l.ID = selectedDepartmentID)
                    assetToEdit.BarcodeID = formBarcodeID

                    assetToEdit.Fields.Clear()

                    For Each field In AssetCustomField.RetrieveAllActiveByType(CustomFieldType.DropDown)
                        Dim formFieldValue As String = collection(String.Format("ddField_{0}", field.ID))
                        Dim oldFieldValue As String = field.Values
                        Dim newField As New AssetField()
                        newField.FieldName = field.FieldName
                        newField.FieldValue = formFieldValue
                        newField.SourceID = field.ID
                        assetToEdit.Fields.Add(newField)
                        If field.Mandatory AndAlso String.IsNullOrEmpty(formFieldValue) Then
                            ModelState.AddModelError(String.Format("ddField_{0}", field.ID), String.Format("{0} is required.", field.FieldName))
                        End If
                        If formFieldValue <> oldFieldValue Then
                            changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, field.FieldName, oldFieldValue, formFieldValue))
                        End If
                        ViewData(String.Format("ddField_{0}", field.ID)) = formFieldValue
                    Next

                    For Each field In AssetCustomField.RetrieveAllActiveByType(CustomFieldType.Text)
                        Dim formFieldValue As String = collection(String.Format("textField_{0}", field.ID))
                        Dim newField As New AssetField()
                        Dim oldFieldValue As String = field.Values
                        newField.FieldName = field.FieldName
                        newField.FieldValue = formFieldValue
                        newField.SourceID = field.ID
                        assetToEdit.Fields.Add(newField)
                        If field.Mandatory AndAlso String.IsNullOrEmpty(formFieldValue) Then
                            ModelState.AddModelError(String.Format("textField_{0}", field.ID), String.Format("{0} is required.", field.FieldName))
                        End If
                        If formFieldValue <> oldFieldValue Then
                            changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, field.FieldName, oldFieldValue, formFieldValue))
                        End If
                        ViewData(String.Format("textField_{0}", field.ID)) = formFieldValue
                    Next

                    Dim selectedSiteId As Integer = 0
                    Dim department As SiteDepartment = SiteDepartment.GetByPrimaryKey(selectedDepartmentID)
                    If department IsNot Nothing Then
                        selectedSiteId = department.ParentID
                    End If

                    If Not ModelState.IsValid Then
                        InitAssetPageElements(selectedAssetTypeID, selectedDepartmentID, selectedSiteId, "AssetName", formAssetName, _
                                              "ModelNo", formModelNo, "SerialNo", formSerialNo, "BarcodeID", formBarcodeID)
                        Return View()
                    End If

                    assetToEdit.Save()

                    ' Create changes
                    If oldAssetName <> assetToEdit.AssetName Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Asset Name", oldAssetName, assetToEdit.AssetName))
                    End If

                    If oldModelNo <> assetToEdit.ModelNo Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Model#", oldModelNo, assetToEdit.ModelNo))
                    End If

                    If oldSerialNo <> assetToEdit.SerialNo Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Serial#", oldSerialNo, assetToEdit.SerialNo))
                    End If

                    If oldDepartment <> assetToEdit.SiteDepartment.Description Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Department", assetToEdit.SiteDepartment.Description, formDepartmentID))
                    End If

                    If oldAssetType <> assetToEdit.AssetType.Description Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Asset Type", oldAssetType, assetToEdit.AssetType.Description))
                    End If

                    If oldBarcodeID <> assetToEdit.BarcodeID Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Barcode ID", oldBarcodeID, assetToEdit.BarcodeID))
                    End If

                    ModificationHistory.Insert(EntityType.Asset, formAssetName, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, assetToEdit.AssetID, assetToEdit.SiteDepartment.ParentID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.Asset_Modify, assetToEdit.AssetName, assetToEdit)
                End If

                Return RedirectToAction("Index")

            Catch ex As Exception
                Return View()
            End Try
        End Function
#End Region

#Region "Link Requirements"
        ' GET: /Asset/LinkRequirements/5
        Function LinkRequirements(ByVal id As Integer) As ActionResult

            Dim assetToEdit As Asset = Asset.GetByPrimaryKey(id)

            If assetToEdit IsNot Nothing Then
                ViewData("AssetName") = assetToEdit.AssetName
                Dim allRequirements = Requirement.RetrieveAllByAssetType(assetToEdit.AssetTypeID)
                ViewData("Requirements") = allRequirements
                ViewData("TimeZoneList") = SystemHelper.GetTimeZoneList()
                ViewData("Groups") = GroupManager.GetAllBySiteFor(assetToEdit.SiteDepartment.ParentID, Application.CurrentUserInfo)

                For Each req In allRequirements
                    ViewData(String.Format("ReviewType_{0}", req.ID)) = New SelectList(RequirementReviewLookup.RetrieveAll(), "ID", "Description", RequirementReviewType.NotRequired)
                Next

                For Each assetReq In assetToEdit.AssetRequirements
                    ViewData(String.Format("checkedRequirement_{0}", assetReq.RequirementID)) = True
                    ViewData(String.Format("hfReqStatus_{0}", assetReq.RequirementID)) = (assetReq.Groups.Count <> 0).ToString().ToLower()
                    ViewData(String.Format("hfReviewReqStatus_{0}", assetReq.RequirementID)) = (assetReq.ReviewGroups.Count <> 0).ToString().ToLower()
                    ViewData(String.Format("startDate_{0}", assetReq.RequirementID)) = TimeZoneManager.ConvertToUserTimeStringFor(assetReq.StartDate, False)
                    For Each assetGroup In assetReq.Groups
                        ViewData(String.Format("SelectedGroup_req{0}_goup{1}", assetReq.RequirementID, assetGroup.ID)) = True
                    Next

                    For Each assetGroup In assetReq.ReviewGroups
                        ViewData(String.Format("SelectedReviewGroup_req{0}_goup{1}", assetReq.RequirementID, assetGroup.ID)) = True
                    Next

                    ViewData(String.Format("ReviewType_{0}", assetReq.RequirementID)) = New SelectList(RequirementReviewLookup.RetrieveAll(), "ID", "Description", assetReq.ReviewType)
                    If assetReq.ReviewType <> RequirementReviewType.NotRequired Then
                        ViewData(String.Format("RequiredReviewType_{0}", assetReq.RequirementID)) = True
                    End If

                Next

            End If


            Return View()
        End Function

        ' POST: /Asset/LinkRequirements/5
        <HttpPost()> _
        Function LinkRequirements(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult

            Dim assetToEdit As Asset = Asset.GetByPrimaryKey(id)
            Dim requirements = Requirement.RetrieveAllByAssetType(assetToEdit.AssetTypeID)
            Dim groups = GroupManager.GetAllBySiteFor(assetToEdit.SiteDepartment.ParentID, Application.CurrentUserInfo)

            If assetToEdit IsNot Nothing Then

                Dim oldRequirements As List(Of Requirement) = New List(Of Requirement)
                For Each oldReq As Requirement In assetToEdit.Requirements
                    oldRequirements.Add(oldReq)
                Next

                assetToEdit.Requirements.Clear()

                For Each req In requirements
                    Dim changeDetails As New List(Of String)
                    Dim startDate As DateTime = DateTime.UtcNow
                    Dim selectedRequirement As Boolean = Boolean.Parse(collection(String.Format("chbxRequirement_{0}", req.ID)).Split(",")(0))
                    Dim reviewType As RequirementReviewType = [Enum].Parse(GetType(RequirementReviewType), collection(String.Format("ReviewType_{0}", req.ID)))
                    Dim formStartDate As String = collection(String.Format("txtDate_{0}", req.ID))
                    If Not String.IsNullOrEmpty(formStartDate) AndAlso Not DateTime.TryParse(formStartDate, startDate) Then
                        ModelState.AddModelError(String.Format("startDateErr_{0}", req.ID), "Wrong date format")
                    End If

                    If selectedRequirement Then
                        assetToEdit.Requirements.Add(req)
                        If Not assetToEdit.RequirementDates.ContainsKey(req) Then
                            assetToEdit.RequirementDates.Add(req, startDate.ToUniversalTime())
                        End If

                        If Not assetToEdit.RequirementReviewTypes.ContainsKey(req) Then
                            assetToEdit.RequirementReviewTypes.Add(req, reviewType)
                        End If

                        For Each groupItem In groups
                            Dim selectedGroup As Boolean = Boolean.Parse(collection(String.Format("cbxGroup_req{0}_goup{1}", req.ID, groupItem.ID)).Split(",")(0))
                            Dim selectedReviewGroup As Boolean = Boolean.Parse(collection(String.Format("cbxReviewGroup_req{0}_goup{1}", req.ID, groupItem.ID)).Split(",")(0))
                            If selectedGroup Then
                                Dim groupList As List(Of Group)
                                If Not assetToEdit.RequirementGroups.ContainsKey(req) Then
                                    groupList = New List(Of Group)
                                    assetToEdit.RequirementGroups.Add(req, groupList)
                                Else
                                    groupList = assetToEdit.RequirementGroups(req)
                                End If
                                groupList.Add(groupItem)
                                changeDetails.Add(String.Format(Constants.UI.FIELD_ADD_REQ_GROUP_TEMPLATE, req.Name, String.Empty, groupItem.Description))
                            End If

                            If selectedReviewGroup Then
                                Dim reviewGroupList As List(Of Group)
                                If Not assetToEdit.RequirementReviewGroups.ContainsKey(req) Then
                                    reviewGroupList = New List(Of Group)
                                    assetToEdit.RequirementReviewGroups.Add(req, reviewGroupList)
                                Else
                                    reviewGroupList = assetToEdit.RequirementReviewGroups(req)
                                End If
                                reviewGroupList.Add(groupItem)
                                changeDetails.Add(String.Format(Constants.UI.FIELD_ADD_REQ_GROUP_TEMPLATE, req.Name, "Review", groupItem.Description))
                            End If
                        Next
                        Dim oldReq As Requirement = oldRequirements.FirstOrDefault(Function(r) r.ID = req.ID)
                        If oldReq Is Nothing Then
                            ModificationHistory.Insert(EntityType.Asset, assetToEdit.AssetName, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, assetToEdit.AssetID, assetToEdit.SiteDepartment.ParentID)
                        End If
                    End If
                Next
            End If

            If ModelState.IsValid Then
                assetToEdit.Save()
            End If

            assetToEdit = Asset.GetByPrimaryKey(assetToEdit.AssetID)

            ViewData("AssetName") = assetToEdit.AssetName
            ViewData("Requirements") = requirements
            ViewData("TimeZoneList") = SystemHelper.GetTimeZoneList()
            ViewData("Groups") = groups

            For Each req In requirements
                ViewData(String.Format("ReviewType_{0}", req.ID)) = New SelectList(RequirementReviewLookup.RetrieveAll(), "ID", "Description", RequirementReviewType.NotRequired)
            Next

            For Each assetReq In assetToEdit.AssetRequirements
                ViewData(String.Format("hfReqStatus_{0}", assetReq.RequirementID)) = (assetReq.Groups.Count <> 0).ToString().ToLower()
                ViewData(String.Format("hfReviewReqStatus_{0}", assetReq.RequirementID)) = (assetReq.ReviewGroups.Count <> 0).ToString().ToLower()
                ViewData(String.Format("checkedRequirement_{0}", assetReq.RequirementID)) = True
                ViewData(String.Format("startDate_{0}", assetReq.RequirementID)) = TimeZoneManager.ConvertToUserTimeStringFor(assetReq.StartDate, False)
                For Each assetGroup In assetReq.Groups
                    ViewData(String.Format("SelectedGroup_req{0}_goup{1}", assetReq.RequirementID, assetGroup.ID)) = True
                Next

                For Each assetGroup In assetReq.ReviewGroups
                    ViewData(String.Format("SelectedReviewGroup_req{0}_goup{1}", assetReq.RequirementID, assetGroup.ID)) = True
                Next

                ViewData(String.Format("ReviewType_{0}", assetReq.RequirementID)) = New SelectList(RequirementReviewLookup.RetrieveAll(), "ID", "Description", assetReq.ReviewType)
                If assetReq.ReviewType <> RequirementReviewType.NotRequired Then
                    ViewData(String.Format("RequiredReviewType_{0}", assetReq.RequirementID)) = True
                End If
            Next

            Return View()
        End Function

#End Region

#Region "AJAX"

        <HttpPost()> _
        Function GetDepartmentDDBySiteID(ByVal siteID As Integer?) As ActionResult
            If Not siteID.HasValue Then
                siteID = 0
            End If
            ViewData("Department") = New SelectList(SiteDepartmentManager.RetrieveAllDepartmentsBySite(siteID), "ID", "Description")
            Return PartialView("~/Views/Asset/Controls/AllDepartmentDropDown.ascx")
        End Function

        <HttpPost()> _
        Function FilterAsset(ByVal assetTypeID As Integer?, ByVal siteID As Integer?, ByVal depID As Integer?) As ActionResult

            If Not assetTypeID.HasValue Then
                assetTypeID = 0
            End If
            If Not siteID.HasValue Then
                siteID = 0
            End If
            If Not depID.HasValue Then
                depID = 0
            End If

            ViewData("Assets") = AssetManager.GetFilteredFor(Application.CurrentUserInfo, assetTypeID, siteID, depID)

            Return PartialView("~/Views/Asset/Controls/AssetGrid.ascx")
        End Function


        <HttpPost()> _
        Function ShangeAssetStatus(ByVal assetID As Integer, ByVal statusID As Integer) As JsonResult
            Dim actionResult As New JSONActionResult
            actionResult.Result = Result.SUCCESS
            Try
                Dim assetToChange = Asset.GetByPrimaryKey(assetID)
                Dim changeDetails As New List(Of String)
                Dim oldStatus As String = assetToChange.AssetStatus.Description
                assetToChange.AssetStatus = assetToChange.DBContext.AssetStatus.Single(Function(s) s.ID = statusID)
                assetToChange.Save()
                If oldStatus <> assetToChange.AssetStatus.Description Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Status", oldStatus, assetToChange.AssetStatus.Description))
                    ModificationHistory.Insert(EntityType.Asset, assetToChange.AssetName, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, Application.CurrentUserInfo.UserID, assetToChange.SiteDepartment.ParentID)
                End If

            Catch ex As Exception
                actionResult.Result = Result.ERROR
                actionResult.Message = ex.Message
            End Try

            Return Json(actionResult)
        End Function

        <HttpPost()> _
        Function CheckBarCode(ByVal locID As Integer, ByVal barCode As String) As JsonResult
            Dim actionResult As New JSONActionResult
            actionResult.Result = Result.SUCCESS
            Try
                Dim location = SiteDepartment.GetByPrimaryKey(locID)
                Dim assetToCheck = Asset.RetrieveAllBySiteIDAndBarCode(location.ParentID, barCode)

                If assetToCheck.Count() > 0 Then
                    actionResult.Result = Result.ERROR
                    actionResult.Message = "This barcode already exists"
                End If

            Catch ex As Exception
                actionResult.Result = Result.ERROR
                actionResult.Message = ex.Message
            End Try

            Return Json(actionResult)
        End Function

        <HttpPost()> _
        Function GetDepartmentsBySite(ByVal id As Integer) As ActionResult
            Dim groups As IEnumerable(Of Group) = GroupManager.GetAllByDepartmentFor(id, Application.CurrentUserInfo)

            ViewData("Group") = New SelectList(groups, "ID", "Description")

            Dim locations As IEnumerable(Of SiteDepartment) = SiteDepartmentManager.GetAllDepartmentsBySiteFor(id, Application.CurrentUserInfo)
            Dim formatedDepartmentList = locations.Select(Function(l) New With {.ID = l.ID, .Description = String.Format("{0}/{1}", l.Parent.Description, l.Description)})


            Dim selectedDepartment = formatedDepartmentList.FirstOrDefault()
            If selectedDepartment IsNot Nothing Then
                ViewData("Department") = New SelectList(formatedDepartmentList, "ID", "Description", selectedDepartment.ID)
            Else
                ViewData("Department") = New SelectList(formatedDepartmentList, "ID", "Description")
            End If


            Return PartialView("~/Views/Asset/Controls/DepartmentDropDown.ascx")
        End Function
#End Region

#Region "Delete"

        ' GET: /Asset/Delete/5
        Function Delete(ByVal id As Integer) As ActionResult
            Return View()
        End Function

        ' POST: /Asset/Delete/5
        <HttpPost()> _
        Function Delete(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
            Try
                ' TODO: Add delete logic here

                Return RedirectToAction("Index")
            Catch
                Return View()
            End Try
        End Function

#End Region

#Region "NotFound"
        Function NotFound(ByVal id As String) As ActionResult
            Dim isNameMsg As Boolean = Not String.IsNullOrEmpty(Request.QueryString("name"))
            If isNameMsg Then
                ViewData("isName") = Boolean.TrueString
            End If
            ViewData("id") = id
            Return View()
        End Function
#End Region

#Region "Private Section"
        Private Sub InitAssetPageElements(ByVal selectedTypeID As Integer, ByVal selectedDepartmentID As Integer, ByVal selectedSiteID As Integer, ByVal ParamArray params As String())

            InitAssetPageElements(selectedTypeID, selectedDepartmentID, selectedSiteID)

            For i As Integer = 0 To params.Length Step 2
                Dim fieldAlias As String = params(i)
                Dim fieldValue As String = params(i + 1)
                ViewData(fieldAlias) = fieldValue
            Next

        End Sub

        Private Sub InitAssetPageElements(ByVal selectedTypeID As Integer, ByVal selectedDepartmentID As Integer, ByVal selectedSiteID As Integer)

            Dim groups As IEnumerable(Of Group) = GroupManager.GetAllByDepartmentFor(selectedDepartmentID, Application.CurrentUserInfo)
            Dim locations As IEnumerable(Of SiteDepartment) = SiteDepartmentManager.GetAllDepartmentsFor(Application.CurrentUserInfo)
            Dim formatedDepartmentList = locations.Select(Function(l) New With {.ID = l.ID, .Description = String.Format("{0}/{1}", l.Parent.Description, l.Description)})
            Dim sites As IEnumerable(Of SiteDepartment) = SiteDepartmentManager.GetAllSitesFor(Application.CurrentUserInfo)

            ViewData("Site") = New SelectList(sites, "ID", "Description", selectedSiteID)
            ViewData("Department") = New SelectList(formatedDepartmentList, "ID", "Description", selectedDepartmentID)
            ViewData("AssetType") = New SelectList(AssetType.RetrieveAll(), "ID", "Description", selectedTypeID)
            ViewData("CustomTextFields") = AssetCustomField.RetrieveAllActiveByType(CustomFieldType.Text)
            ViewData("CustomDDFields") = AssetCustomField.RetrieveAllActiveByType(CustomFieldType.DropDown)
            ViewData("Statuses") = AssetStatus.RetrieveAll()
            InitRequiredFields()
        End Sub

        Private Sub InitAssetPageElements()
            Dim groups As IEnumerable(Of Group) = New List(Of Group)
            Dim sites As IEnumerable(Of SiteDepartment) = SiteDepartmentManager.GetAllSitesFor(Application.CurrentUserInfo)

            Dim selectedSite = sites.FirstOrDefault()
            If selectedSite IsNot Nothing Then
                ViewData("Site") = New SelectList(sites, "ID", "Description", selectedSite.ID)
            Else
                ViewData("Site") = New SelectList(sites, "ID", "Description")
            End If

            Dim locations As IEnumerable(Of SiteDepartment) = SiteDepartmentManager.GetAllDepartmentsBySiteFor(selectedSite.ID, Application.CurrentUserInfo)
            Dim formatedDepartmentList = locations.Select(Function(l) New With {.ID = l.ID, .Description = String.Format("{0}/{1}", l.Parent.Description, l.Description)})


            Dim selectedDepartment = formatedDepartmentList.FirstOrDefault()
            If selectedDepartment IsNot Nothing Then
                ViewData("Department") = New SelectList(formatedDepartmentList, "ID", "Description", selectedDepartment.ID)
            Else
                ViewData("Department") = New SelectList(formatedDepartmentList, "ID", "Description")
            End If

            ViewData("AssetType") = New SelectList(AssetType.RetrieveAll(), "ID", "Description")

            ViewData("CustomTextFields") = AssetCustomField.RetrieveAllActiveByType(CustomFieldType.Text)
            ViewData("CustomDDFields") = AssetCustomField.RetrieveAllActiveByType(CustomFieldType.DropDown)
            ViewData("Statuses") = AssetStatus.RetrieveAll()
            InitRequiredFields()

        End Sub

        Private Sub InitRequiredFields()
            Dim predefinedFieldList = AssetCustomField.RetrieveAllByType(CustomFieldType.Predefined)
            For Each field In AssetPredefinedFieldLookup.RetrieveAll()
                Dim seq As Integer = CInt(field.Type)
                Dim dbField As AssetCustomField = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = seq)

                If dbField IsNot Nothing Then
                    field.Selected = dbField.Mandatory
                Else
                    field.Selected = False
                End If
                If field.Selected Then
                    ViewData(String.Format("{0}Required", field.Type.ToString())) = True
                End If
            Next
        End Sub
#End Region
    End Class
End Namespace